package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Size;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private GreenTextScan textScan;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    CommentHotService commentHotService;

    /**
     * 保存评论
     *
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        System.out.println("保存方法触发");
//        1. 校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

//         2.  校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "用户没有登录不能评论");
        }
//       3. 校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验)
        if (StringUtils.isBlank(dto.getContent()) || dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (StringUtils.isNotBlank(dto.getContent()) && dto.getContent().length() > 140) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "内容长度不能大于140个字符");
        }
//        2. 阿里云校验评论内容是否违规 有问题不报异常，替换为**
        String content = handleTextScan(dto.getContent());

//        3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> responseResult = userFeign.findUserById(user.getId());
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApUser apUser = responseResult.getData();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的用户信息不存在");
        }
        //  4. 创建评论信息，并保存到mongo
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setArticleId(dto.getArticleId());
//            apComment.setType();
//            apComment.setChannelId();
        apComment.setContent(content);
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        mongoTemplate.insert(apComment);
//        mongoTemplate.save(apComment);
        return ResponseResult.okResult(apComment);
    }

    /**
     * 根据文章id查询评论列表
     *
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
//        1. 参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//       1.1 校验文章id
        if (dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章id不能为空");
        }
//       1.2 校验size
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
//        2. 根据条件查询评论列表 (文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
//        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
//                .and("createdTime").lt(dto.getMinDate()));
//        query.limit(dto.getSize());
//        query.with(Sort.by(
//                Sort.Order.desc("createdTime")
//        ));
//        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);

        List<ApComment> apCommentList = null;
        if (dto.getIndex().intValue() == 1) {
            // 先查询热点评论集合  （最多5条） (条件: flag=1, 文章id, 点赞降序)
            Query query2 = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(1));
            query2.limit(5);
            query2.with(Sort.by(
                    Sort.Order.desc("likes")
            ));
//            List<ApComment> hotCommentList = mongoTemplate.find(query2, ApComment.class);
            apCommentList = mongoTemplate.find(query2, ApComment.class);
            // 新size = size - 热评数量
            int size = dto.getSize() - apCommentList.size();
            // 查询第一页剩余普通评论 (条件: 文章id, flag=0, 时间降序, limit:新size)
            Query query3 = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(0));
            query3.limit(size);
            query3.with(Sort.by(
                    Sort.Order.desc("createdTime")
            ));
            List<ApComment> commentList = mongoTemplate.find(query3, ApComment.class);
            // 合并 热点评论  普通评论   热点list.addAll(普通list)
            apCommentList.addAll(commentList);
//            apCommentList = commentList;
        } else {
            // 不是第一页直接查询普通评论
            // (条件: 文章id,flag=0,createdTime小于最小时间,时间降序,limit:size)
            Query query4 = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is(0).and("createdTime").lt(dto.getMinDate()));
            query4.limit(dto.getSize());
            query4.with(Sort.by(
                    Sort.Order.desc("createdTime")
            ));
            apCommentList = mongoTemplate.find(query4, ApComment.class);
        }
//        3. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            // 4. 如果未登录直接返回评论列表
            return ResponseResult.okResult(apCommentList);
        }
//        5. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        List<String> list = apCommentList.stream().map(ApComment::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(list)
                .and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
//        if (apCommentLikes == null){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
//        }
        //  (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
        List<ApCommentVo> voList = new ArrayList<>();
        for (ApComment apComment : apCommentList) {
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment, apCommentVo);
            if (apCommentLikes.size() == 0) {
                return ResponseResult.okResult(apCommentList);
            }
            for (ApCommentLike apCommentLike : apCommentLikes) {
                if (apCommentLike.getCommentId().equals(apComment.getId())) {
                    apCommentVo.setOperation((short) 0);
                }
            }
            voList.add(apCommentVo);
        }
        return ResponseResult.okResult(voList);
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {

//        1. 参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前用户为登录");
        }
//        评论id不能为空  operation必须为 0  或  1
        if (StringUtils.isBlank(dto.getCommentId())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论id不能为空");
        }
        if (dto.getOperation() != 0 && dto.getOperation() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "当前点赞操作异常");
        }
//        2. 根据评论id查询评论数据， 为返回错误信息
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        Query query1 = Query.query(Criteria.where("authorId").is(user.getId()).
                and("commentId").is(dto.getCommentId()));
        ApCommentLike apCommentLike = mongoTemplate.findOne(query1, ApCommentLike.class);
        Map<String, Integer> data = new HashMap();
        if (dto.getOperation() == 0) {
            // 点赞操作时
            if (apCommentLike != null) {
                //  点过赞提示 请勿重复点赞
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
            }
            // 未点过赞   保存点赞信息到mongo
            ApCommentLike commentLike = new ApCommentLike();
            commentLike.setAuthorId(user.getId());
            commentLike.setCommentId(dto.getCommentId());
            commentLike.setOperation((short) 0);
            mongoTemplate.save(commentLike);
            // 并修改评论信息的点赞数量( + 1)
            Integer likes = apComment.getLikes();
            apComment.setLikes(likes + 1);
            mongoTemplate.save(apComment);
            // 判断 如果点赞数量大于等于10 ， 并且当前评论还是普通评论 (flag = 0)
            //调用计算热点评论方法
            if (apComment.getLikes() >= 10 && apComment.getFlag() == 0) {
                commentHotService.hotCommentExecutor(apComment);
            }
            data.put("likes", apComment.getLikes());
            return ResponseResult.okResult(data);
        }
//        4. 如果是取消点赞操作  删除点赞信息
        mongoTemplate.remove(query1, ApCommentLike.class);
//        并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
        Integer likes = apComment.getLikes();
        if (likes >= 1) {
            apComment.setLikes(likes - 1);
            mongoTemplate.save(apComment);
            data.put("likes", apComment.getLikes());
            return ResponseResult.okResult(data);
        } else {
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前不能执行取消点赞");
            data.put("likes", apComment.getLikes());
            return ResponseResult.okResult(data);
        }
    }

    /**
     * 阿里云的文本审核
     *
     * @param content
     * @return
     */
    private String handleTextScan(String content) {
        try {
            Map map = textScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            if (!suggestion.equals("pass")) {
                String content1 = map.get("filteredContent").toString();
                return content1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
}
